package com.sks.web.action.deployment;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;

import com.sks.bean.QueryResult;
import com.sks.bean.pojo.Area;
import com.sks.bean.pojo.Config;
import com.sks.bean.pojo.House;
import com.sks.bean.pojo.HouseType;
import com.sks.bean.pojo.Metro;
import com.sks.bean.pojo.MetroStation;
import com.sks.bean.pojo.PropertyType;
import com.sks.bean.pojo.Users;
import com.sks.service.house.AreaService;
import com.sks.service.house.BuildingService;
import com.sks.service.house.ConfigService;
import com.sks.service.house.HouseService;
import com.sks.service.house.HouseTypeService;
import com.sks.service.house.MetroService;
import com.sks.service.house.MetroStationService;
import com.sks.service.house.PropertyTypeService;
import com.sks.service.privilege.UsersService;
import com.sks.utils.StringUtil;
import com.sks.utils.WebUtil;
import com.sks.web.action.BasicAction;
import com.sks.web.action.privilege.Permission;
import com.sks.web.formbean.house.HouseForm;
import com.sks.web.formbean.house.MetroForm;

import flexjson.JSONSerializer;

/**
 * @description 类描述
 * @author duof
 * @update 2012-2-26 下午5:15:04
 */

@Controller("/sks/frontpages/privilege/deployment/manage")
public class DeploymentManageAction extends BasicAction {

	@Resource(name = "houseServiceBean")
	private HouseService service;

	@Resource(name = "configServiceBean")
	private ConfigService configService;

	@Resource(name = "houseTypeServiceBean")
	private HouseTypeService houseTypeService;

	@Resource(name = "areaServiceBean")
	private AreaService areaService;

	@Resource(name = "propertyTypeServiceBean")
	private PropertyTypeService propertyTypeService;

	@Resource(name = "metroStationServiceBean")
	private MetroStationService metroStationService;

	@Resource(name = "metroServiceBean")
	private MetroService metroService;

	@Resource(name = "buildingServiceBean")
	private BuildingService buildingService;
	
	@Resource
	UsersService usersService;

	protected static String[] transFields = { "indate", "linkMan", "mobile",
			"transaStatus", "rentPrice", "rentMode", "rentPayTypeId",
			"rentShareInfo", "houseProperty", "salePayTypeId", "salePrice" };

	protected static String[] auditFields = { "employeeName", "createTime",
			"lastUpdateTime" };

	protected static String[] hideFields = { "houseStatus", "auditTime",
			"publishTime" };

	/*
	 * houseform表单有，但是编辑房源页面没有的属性
	 * 
	 * houseId、userId、userName、salePayTypeId、employeeName、
	 * rentPayTypeId、propertyTypeId、buildingId、hits、linkMan、
	 * mobile、rentPrice、rentMode、rentShareInfo、houseProperty、
	 * salePrice、houseStatus、createTime、auditTime、publishTime、
	 * finishTime、isHot、type、orderBy、menuName、maxPrice、minPrice、
	 * isRent、changeOrderBy、commentIds、commentId、content、 revertTime、revertTime
	 */
	protected static String[] ignoreProperties = { "houseId", "userId",
			"userName", "salePayTypeId", "employeeName", "rentPayTypeId",
			"propertyTypeId", "buildingId", "hits", "linkMan", "mobile",
			"rentPrice", "rentMode", "rentShareInfo", "houseProperty",
			"salePrice", "houseStatus", "createTime", "auditTime",
			"publishTime", "lastUpdateTime", "finishTime", "isHot", "type",
			"orderBy", "menuName", "maxPrice", "minPrice", "isRent",
			"changeOrderBy", "commentIds", "commentId", "content",
			"revertTime", "revertTime" };

	protected static String[] onlyBase = mergeArrays(hideFields, transFields,
			auditFields);

	protected static void copyProperties(Object source, Object target,
			String type) {
		String[] ignorePros = null;
		if ("ignoreProperties".equals(type)) {
			ignorePros = ignoreProperties;
		}
		BeanUtils.copyProperties(source, target, ignorePros);
	}

	/**
	 * @param strings
	 * @return
	 * @description 将strings数组拼成一个字符串
	 * @update 2012-3-13 下午9:49:21
	 */
	private static String[] mergeArrays(String[]... strings) {
		Integer newLen = 0;
		for (String[] strs : strings) {
			newLen += strs.length;
		}
		String[] newArray = new String[newLen];
		Integer temp = 0;
		for (int i = 0; i < strings.length; i++) {
			String[] strs = strings[i];
			System.arraycopy(strs, 0, newArray, temp, strs.length);
			temp += strs.length;
		}
		return newArray;
	}

	/**
	 * @param mapping
	 *            将特定请求映射到特定Action的相关信息存储在ActionMapping中
	 * @param form
	 *            房源表单
	 * @param request
	 *            请求
	 * @param response
	 *            响应
	 * @return 返回具体页面标志
	 * @throws Exception
	 *             修改用户的房源
	 * @description 将用户修改的房源信息保存
	 * @update 2012-2-26 下午4:08:26
	 */
	@Permission(module = "users", privilege = "update")
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		this.saveToken(request);
		HouseForm formbean = (HouseForm) form;
		House house = new House();
		copyProperties(formbean, house, "Base");
		// 生成一些默认的配置
		Date time = new Date();
		house.setCreateTime(time);
		house.setLastUpdateTime(time);
		house.setHouseStatus(House.HOUSE_STATUS_NONE_SUBMIT);
		house.setUsers(WebUtil.getUsers(request));
		house.setIsHot(false);
		setObjectInHouse(house, formbean);
		if(house.getSpace() != null && !("").equals(house.getSpace()) ){
			DecimalFormat df = new DecimalFormat("0.00");
			String db = df.format(house.getSpace());
			house.setSpace(Double.parseDouble(db));
		}
		service.save(house);
		return mapping.findForward(LIST); // 进入管理房源页面
	}
	
	public void beforeedit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		this.beforeadd(mapping, form, request, response);
	}
	
	public void beforeadd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ActionMessages errors = new ActionErrors();
		HouseForm formbean = (HouseForm) form;
		
		if (StringUtil.isEmpty(formbean.getTitle())) {
			errors.add("title", new ActionMessage("errors.required", getMessage("info.house.field.title")));
		}
		
		List params = new ArrayList();
		params.add(formbean.getTitle());
		StringBuffer jpql = new StringBuffer("o.title = ?" + params.size());
		if (EDIT.equals(formbean.getMethod())) {
			params.add(formbean.getHouseId());
			jpql.append(" and o.houseId <> ?" + params.size());
		}
		QueryResult<House> m = service.getScrollData(-1, -1, jpql.toString(),
				params.toArray());
		
		if (null != m && m.getResultlist().size() > 0) {
			// 提示信息
			errors.add("title", new ActionMessage("errors.repeat", getMessage("info.house.field.title")));
			getBaseData(request, formbean);
		}
		saveErrors(request, errors);
	}

	/**
	 * @param mapping
	 *            将特定请求映射到特定Action的相关信息存储在ActionMapping中
	 * @param form
	 *            房源表单
	 * @param request
	 *            请求
	 * @param response
	 *            响应
	 * @return 返回具体页面标志
	 * @throws Exception
	 * @description 方法描述 重置返回的路径为add。
	 * @update 2012-2-26 下午3:52:35
	 */
	@Permission(module = "users", privilege = "view")
	public ActionForward addUI(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		this.saveToken(request);
		HouseForm formbean = (HouseForm) form;
		getBaseData(request, formbean);
		formbean.setMethod(ADD);
		return mapping.findForward(EDIT); // 进入编辑页面
	}

	/**
	 * @param mapping
	 *            将特定请求映射到特定Action的相关信息存储在ActionMapping中
	 * @param form
	 *            房源表单
	 * @param request
	 *            请求
	 * @param response
	 *            响应
	 * @return 返回具体页面标志
	 * @throws Exception
	 *             修改用户的房源
	 * @description 删除房源信息
	 * @update 2012-2-26 下午4:08:26
	 */
	@Permission(module = "users", privilege = "update")
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		this.saveToken(request);
		HouseForm formbean = (HouseForm) form;
		House house = service.find(formbean.getHouseId());
		if (null == house) {
			request.setAttribute("forwardTo", "/sks/frontpages/privilege/deployment/list.do");
			return mapping.findForward("noHouse");
		}
		Users user = house.getUsers();
		Users current = WebUtil.getUsers(request);
		if (null == user || !user.getLoginName().equals(current.getLoginName())) {
			request.setAttribute("forwardTo", "/sks/frontpages/privilege/deployment/list.do");
			return mapping.findForward("noHouse");
		}
		
		if (!House.HOUSE_STATUS_NONE_SUBMIT.equals(house.getHouseStatus())) {
			request.setAttribute("errorMsg", "只能删除未提交的房源！");
		} else {
			service.delete(formbean.getHouseId());
		}
		return mapping.findForward(LIST); // 进入管理房源页面
	}

	/**
	 * @param mapping
	 *            将特定请求映射到特定Action的相关信息存储在ActionMapping中
	 * @param form
	 *            房源表单
	 * @param request
	 *            请求
	 * @param response
	 *            响应
	 * @return 返回具体页面标志
	 * @throws Exception
	 *             修改用户的房源
	 * @description 将用户修改的房源信息保存
	 * @update 2012-2-26 下午4:08:26
	 */
	@Permission(module = "users", privilege = "update")
	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		HouseForm formbean = (HouseForm) form;
		House house = service.find(formbean.getHouseId());
		if (House.HOUSE_STATUS_NONE_SUBMIT.equals(house.getHouseStatus())) {
		
			if (null == house) {
				request.setAttribute("forwardTo", "/sks/frontpages/privilege/deployment/list.do");
				return mapping.findForward("noHouse");
			}
			Users user = house.getUsers();
			Users current = WebUtil.getUsers(request);
			if (null == user || !user.getLoginName().equals(current.getLoginName())) {
				request.setAttribute("forwardTo", "/sks/frontpages/privilege/deployment/list.do");
				return mapping.findForward("noHouse");
			}
			
			house.setLastUpdateTime(new Date());
			house.setIsHot(false);
			copyProperties(formbean, house, "ignoreProperties");
	
			setObjectInHouse(house, formbean);
			if(house.getSpace() != null && !("").equals(house.getSpace()) ){
				DecimalFormat df = new DecimalFormat("0.00");
				String db = df.format(house.getSpace());
				house.setSpace(Double.parseDouble(db));
			}
			if(formbean.getSaveAndSubmitFlag()){
				house.setHouseStatus(House.HOUSE_STATUS_NONE_AUDIT);
			}
			service.update(house);
		}
		return mapping.findForward(LIST); // 进入管理房源页面
	}

	/**
	 * @param mapping
	 *            将特定请求映射到特定Action的相关信息存储在ActionMapping中
	 * @param form
	 *            房源表单
	 * @param request
	 *            请求
	 * @param response
	 *            响应
	 * @return 返回具体页面标志
	 * @throws Exception
	 * @description 方法描述 通过房源houseId拿到房源再跳到房源的编辑页面进行修改功能。
	 * @update 2012-2-26 下午3:52:35
	 */
	@Permission(module = "users", privilege = "view")
	public ActionForward editDeploymentUI(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		this.saveToken(request);
		HouseForm formbean = (HouseForm) form;
		House house = service.find(formbean.getHouseId());
		
		if (null == house) {
			request.setAttribute("forwardTo", "/sks/frontpages/privilege/deployment/list.do");
			return mapping.findForward("noHouse");
		}
		Users user = house.getUsers();
		Users current = WebUtil.getUsers(request);
		if (null == user || !user.getLoginName().equals(current.getLoginName())) {
			request.setAttribute("forwardTo", "/sks/frontpages/privilege/deployment/list.do");
			return mapping.findForward("noHouse");
		}
		
		copyProperties(house, formbean, "ignoreProperties");
		getBaseData(request, formbean);
		formbean.setBuildingName(null != house.getBuilding() ? house
				.getBuilding().getName() : null);
		request.setAttribute("selectedConfigs", house.getConfigs());
		formbean.setMethod(EDIT);
		
		boolean readOnly = true;
		if (House.HOUSE_STATUS_NONE_SUBMIT.equals(house.getHouseStatus())) {
			readOnly = false;
		}
		
		request.setAttribute("readOnly", readOnly);
		
		return mapping.findForward(EDIT); // 进入编辑页面
	}

	/**
	 * @param request
	 * @param formbean
	 * @description 获取房源的基本信息
	 * @update 2012-3-8 下午10:06:25
	 */
	private void getBaseData(HttpServletRequest request, HouseForm formbean) {
		List<Config> cs = configService.getScrollData().getResultlist();
		List<HouseType> hts = houseTypeService.getScrollData().getResultlist();
		List<MetroStation> mss = new ArrayList<MetroStation>(0);
		List<Metro> ms = metroService.getScrollData().getResultlist();
		if (null != formbean.getMetroStationId()) {
			MetroStation stasion = metroStationService.find(formbean
					.getMetroStationId());
			if (null != stasion.getMetroByMetroId()) {
				mss.addAll(stasion.getMetroByMetroId()
						.getMetroStationsForMetroId());
				formbean.setMetroId(stasion.getMetroByMetroId().getMetroId());
			} else if (null != stasion.getMetroByMetroId1()) {
				mss.addAll(stasion.getMetroByMetroId1()
						.getMetroStationsForMetroId());
				formbean.setMetroId(stasion.getMetroByMetroId1().getMetroId());
			}
		} else {
			formbean.setMetroId(null);
		}

		List<Area> tops = areaService.findAreas(true, null);
		List<Area> lows = new ArrayList<Area>(0);
		Integer areaId = formbean.getAreaId();
		if (null != areaId) {
			Area area = areaService.find(areaId);
			lows.addAll(area.getParentArea().getAreas());
			formbean.setTopAreaId(area.getParentArea().getAreaId());
		} else {
			formbean.setTopAreaId(null);
		}
		List<PropertyType> ppts = propertyTypeService.getScrollData()
				.getResultlist();

		request.setAttribute("cs", cs);
		request.setAttribute("hts", hts);
		request.setAttribute("mss", mss);
		request.setAttribute("ms", ms);
		request.setAttribute("ppts", ppts);
		request.setAttribute("tops", tops);
		request.setAttribute("lows", lows);
	}

	/**
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @description 根据地铁线得到地铁站名
	 * @update 2012-3-8 下午10:57:51
	 */
	public ActionForward getStations(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		MetroForm formbean = (MetroForm) form;
		if (null == formbean.getMetroId() || 0 == formbean.getMetroId()) {
			response.getWriter().write("[{\"name\":\"\",\"areaId\":\"\"}]");
			return null;
		}
		Metro topMetro = metroService.find(formbean.getMetroId());
		List<MetroStation> mss = topMetro.getMetroStationsForMetroId();
		JSONSerializer json = new JSONSerializer();
		String jsonStr = json.exclude("*.class", "metroByMetroId",
				"metroByMetroId1", "isIntersect", "remark", "metroId",
				"metroId1").include("stationId", "name").serialize(mss);
		response.getWriter().write(jsonStr);
		return null;
	}

	/**
	 * @param house
	 *            房源
	 * @param formbean
	 *            房源表单
	 * @description 方法描述 将house的一些附属的属性赋给它
	 * @update 2012-2-26 下午4:37:23
	 */
	private void setObjectInHouse(House house, HouseForm formbean) {
		house
				.setBuilding(buildingService.find(formbean.getBuildingId(),
						false));
		house.setArea(areaService.find(formbean.getAreaId(), false));
		house.setHouseType(houseTypeService.find(formbean.getHouseTypeId(),
				false));
		house.setMetroStation(metroStationService.find(formbean
				.getMetroStationId(), false));
		house.setPropertyType(propertyTypeService.find(formbean
				.getPropertyTypeId(), false));

		Set<Config> cons = house.getConfigs();
		if (null == cons) {
			cons = new HashSet<Config>(0);
		} else {
			cons.clear();
		}
		if (null != formbean.getConfigIds()) {
			for (Integer configId : formbean.getConfigIds()) {
				Config c = configService.find(configId);
				cons.add(c);
			}
		}
		house.setConfigs(cons);
	}

	public ActionForward changeStatus(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HouseForm formbean = (HouseForm) form;
		House house = service.find(formbean.getHouseId());
		if (null == house) {
			request.setAttribute("forwardTo", "/sks/frontpages/privilege/deployment/list.do");
			return mapping.findForward("noHouse");
		}
		Users user = usersService.find(house.getUserId());
		Users current = WebUtil.getUsers(request);
		if (null == user || !user.getLoginName().equals(current.getLoginName())) {
			request.setAttribute("forwardTo", "/sks/frontpages/privilege/deployment/list.do");
			return mapping.findForward("noHouse");
		}
		String oldStatus = house.getHouseStatus();
		String newStatus = formbean.getHouseStatus();
		
		if (House.HOUSE_STATUS_NONE_SUBMIT.equals(oldStatus)) {//未提交
			if (House.HOUSE_STATUS_NONE_AUDIT.equals(newStatus)) {//已提交未审核
				house.setHouseStatus(House.HOUSE_STATUS_NONE_AUDIT);
			}
		} else if (House.HOUSE_STATUS_NONE_AUDIT.equals(oldStatus)) {//已提交未审核
			if (House.HOUSE_STATUS_NONE_SUBMIT.equals(newStatus)) {//撤销已提交未审核 变为 未提交
				house.setHouseStatus(House.HOUSE_STATUS_NONE_SUBMIT);
			}
		}
		
		if (!House.HOUSE_STATUS_NONE_AUDIT.equals(oldStatus) && !House.HOUSE_STATUS_NONE_SUBMIT.equals(oldStatus)) {
			request.setAttribute("errorMsg", "该状态下房源不能修改，请联系sks管理员！");
		}
		
		service.update(house);
		return mapping.findForward("list");
		//return editDeploymentUI(mapping, form, request, response);
	}
}
